/**
 * 番茄钟控制器
 * 处理番茄钟相关的业务逻辑
 */
const pomodoroModel = require('../models/pomodoroModel');
const logger = require('../utils/logger');

const pomodoroController = {
  /**
   * 获取番茄钟历史记录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getHistory: async (req, res, next) => {
    try {
      const userId = req.user.id;
      
      // 提取查询参数
      const filters = {
        date: req.query.date,
        status: req.query.status !== undefined ? parseInt(req.query.status) : undefined,
        task_id: req.query.task_id,
        limit: req.query.limit,
        offset: req.query.offset
      };

      const history = await pomodoroModel.getHistory(userId, filters);
      
      res.json({
        data: history,
        count: history.length
      });
    } catch (error) {
      logger.error(`获取番茄钟历史记录错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 获取番茄钟统计信息
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  getStatistics: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const period = req.query.period || 'day';
      
      const statistics = await pomodoroModel.getStatistics(userId, period);
      
      res.json({
        data: statistics
      });
    } catch (error) {
      logger.error(`获取番茄钟统计信息错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 开始番茄钟
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  startPomodoro: async (req, res, next) => {
    try {
      const userId = req.user.id;
      const pomodoroData = {
        ...req.body,
        user_id: userId
      };

      const pomodoro = await pomodoroModel.start(pomodoroData);
      
      res.status(201).json({
        message: '番茄钟已开始',
        data: pomodoro
      });
    } catch (error) {
      logger.error(`开始番茄钟错误: ${error.message}`);
      next(error);
    }
  },

  /**
   * 结束番茄钟
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   * @param {Function} next - 下一个中间件函数
   */
  endPomodoro: async (req, res, next) => {
    try {
      const pomodoroId = req.params.id;
      const userId = req.user.id;
      const status = parseInt(req.body.status);
      
      // 验证状态值
      if (status !== 1 && status !== 2) {
        return res.status(400).json({ message: '无效的状态值，应为1(完成)或2(中断)' });
      }

      const success = await pomodoroModel.end(pomodoroId, userId, status);
      
      if (!success) {
        return res.status(404).json({ message: '番茄钟不存在或已结束' });
      }

      res.json({
        message: status === 1 ? '番茄钟已完成' : '番茄钟已中断',
        id: pomodoroId
      });
    } catch (error) {
      logger.error(`结束番茄钟错误: ${error.message}`);
      next(error);
    }
  }
};

module.exports = pomodoroController; 